package com.mikey.rw;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author :Mikey
 * @description :ReadWriteLock
 * 读和读：可以共存
 * 读和写：不可以共存
 * 写和写：不可以共存
 * 独占锁：写锁
 * 共享锁：读锁
 * @create :2022-09-21 11:52:00
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        MyCacheLock myCacheLock = new MyCacheLock();
        //读取
        for (int i = 0; i < 5; i++) {
            final int temp = i;
            new Thread(() -> {
                myCacheLock.put(temp + "", temp + "");
            }, String.valueOf(i)).start();
        }
        //写入
        for (int i = 0; i < 5; i++) {
            final int temp = i;
            new Thread(() -> {
                myCacheLock.get(temp + "", temp + "");
            }, String.valueOf(i)).start();
        }
    }
}

//加锁
class MyCacheLock {
    private volatile Map<String, Object> map = new HashMap<>();
    //读写锁，更加细粒度控制，
    private ReadWriteLock lock = new ReentrantReadWriteLock();

    //一个写，多人读
    public void put(String key, Object value) {
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "写入" + key);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName() + "写入ok");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }

    }

    public void get(String key, Object value) {
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "读" + key);
            map.get(key);
            System.out.println(Thread.currentThread().getName() + "读ok");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
    }
}

//自定义缓存
class MyCache {
    private volatile Map<String, Object> map = new HashMap<>();

    public void put(String key, Object value) {
        System.out.println(Thread.currentThread().getName() + "写入" + key);
        map.put(key, value);
        System.out.println(Thread.currentThread().getName() + "写入ok");
    }

    public void get(String key, Object value) {
        System.out.println(Thread.currentThread().getName() + "读" + key);
        map.get(key);
        System.out.println(Thread.currentThread().getName() + "读ok");
    }
}